package ace.module.captcha.core.impl.service.impl;

import ace.module.captcha.api.constant.CaptchaConstant;
import ace.module.captcha.core.impl.dao.entity.CaptchaApplication;
import ace.module.captcha.core.impl.dao.repository.CaptchaApplicationRepository;
import ace.module.captcha.core.impl.dao.repository.CaptchaItemConfigRepository;
import ace.module.captcha.core.impl.manager.CaptchaApplicationManager;
import ace.module.captcha.core.impl.manager.CaptchaItemConfigManager;
import ace.module.captcha.core.impl.service.CaptchaInitService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author caspar
 * @date 2023/8/18 17:42
 */
@Slf4j
@AllArgsConstructor
@Component
public class CaptchaInitServiceImpl implements CaptchaInitService {

  private final CaptchaApplicationRepository captchaApplicationRepository;
  private final CaptchaItemConfigRepository captchaItemConfigRepository;
  private final CaptchaApplicationManager captchaApplicationManager;
  private final CaptchaItemConfigManager captchaItemConfigManager;

  @Transactional(rollbackFor = Exception.class)
  @Override
  public void init() {

    if (captchaApplicationRepository.existsByKey(
        CaptchaConstant.DEFAULT_CAPTCHA_APPLICATION_APP_KEY)) {
      return;
    }

    CaptchaApplication defaultCaptchaApplication =
        this.captchaApplicationManager.getSystemDefault();

    this.captchaItemConfigManager.getSystemDefaultOrCreateByCaptchaAppId(
        defaultCaptchaApplication.getId());

    captchaApplicationRepository.insert(defaultCaptchaApplication);
    log.info("init data success");
  }
}
